package com.sanji.pay.yeepay.service;

import com.sanji.pay.common.utils.DateUtil;
import com.sanji.pay.pay.dto.PayDeal;
import com.sanji.pay.pay.entity.PayOrder;
import com.sanji.pay.pay.repository.PayOrderRepository;
import com.sanji.pay.pay.service.PayOrderService;
import com.sanji.pay.yeepay.entity.YEEPay;
import com.sanji.pay.yeepay.pojo.YEEPayPojo;
import com.sanji.pay.yeepay.repository.YeePayRepository;
import com.yeepay.Configuration;
import com.yeepay.PaymentForOnlineService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by cbh on 2017/9/4.
 */
@Service
public class YeePayServiceImpl implements YeePayService {
  private Logger logger = Logger.getLogger(YeePayServiceImpl.class);
  @Autowired
  private YeePayRepository yeePayRepository;
  @Autowired
  private PayOrderRepository payOrderRepository;
  @Value("${yeePay.p8_Url}")
  public String p8_Url;
  @Autowired
  private PayOrderService payOrderService;

  /**
   * 保存支付信息
   * @param yeePayPojo
   * @return
   */
  @Override
  public YEEPay savePostYeePay(YEEPayPojo yeePayPojo) {
    YEEPay yeePay = yeePayRepository.findByPayNum(yeePayPojo.getP2_Order());
    yeePay = (yeePay != null ) ? yeePay : new YEEPay();
    PayOrder payOrder = payOrderRepository.findByPayNum(yeePayPojo.getP2_Order());
    yeePay.setTrxId(yeePayPojo.getR2_TrxId());
//    Integer amount = yeePayPojo.getP3_Amt() == null ? payOrder.getAmount() : Integer.valueOf(yeePayPojo.getP3_Amt()) * 100;
    yeePay.setAmt(payOrder.getAmount());
    yeePay.setPayNum(yeePayPojo.getP2_Order());
    return yeePayRepository.save(yeePay);
  }

  @Override
  public YEEPay saveReturnYeePay(YEEPayPojo yeePayPojo) {
    YEEPay yeePay = yeePayRepository.findByPayNum(yeePayPojo.getR6_Order());
    yeePay = (yeePay != null ) ? yeePay : new YEEPay();
    yeePay.setTrxId(yeePayPojo.getR2_TrxId());
    //进行价格校验
    PayOrder payOrder = payOrderRepository.findByPayNum(yeePayPojo.getR6_Order());
    double priceValue = Double.parseDouble(yeePayPojo.getR3_Amt());
    if((int)(priceValue * 100) == payOrder.getAmount()){
      yeePay.setAmt(payOrder.getAmount());
    }else{
      yeePay.setAmt(payOrder.getAmount());
    }
    yeePay.setPayNum(yeePayPojo.getR6_Order());
    yeePay.setResultCode(yeePayPojo.getR1_Code());
    yeePay.setPayDate(DateUtil.noformatStringToDate(yeePayPojo.getRp_PayDate(),"yyyy-MM-dd HH:mm:ss"));
    yeePay.setHmac(yeePayPojo.getHmac());
    //保存支付单信息
    payOrder.setDealType("yeePay");
    payOrder.setStatus(PayOrder.PayStatus.SUCCESS);
    payOrder.setPayment(0);
    payOrder.setPayTime(DateUtil.noformatStringToDate(yeePayPojo.getRp_PayDate(),"yyyy-MM-dd HH:mm:ss"));
    payOrderService.save(payOrder);
    return yeePayRepository.save(yeePay);
  }

  @Override
  public YEEPay findByPayNum(String payNum) {
    return yeePayRepository.findByPayNum(payNum);
  }

  /**
   * 调用易宝支付
   * @param payOrder
   * @param pd_FrpId
   * @return
   */
  @Override
  public YEEPayPojo getPayPOJO(PayOrder payOrder, String pd_FrpId) {
    YEEPayPojo yeePayPojo = new YEEPayPojo();
    yeePayPojo.setP0_Cmd("Buy");
    yeePayPojo.setP1_MerId(Configuration.getInstance().getValue("p1_MerId")); // 商户编号
    yeePayPojo.setP2_Order(payOrder.getPayNum());
    yeePayPojo.setP3_Amt(payOrder.getAmount() / 100.00 + "");// 实际支付价格(元为单位,精确到分)
    yeePayPojo.setP4_Cur("CNY");
    yeePayPojo.setP5_Pid("三际手机批发支付");
    yeePayPojo.setP8_Url(p8_Url);
    yeePayPojo.setPd_FrpId(pd_FrpId);
    String hmac = PaymentForOnlineService.getReqMd5HmacForOnlinePayment(formatString(yeePayPojo.getP0_Cmd()), formatString(yeePayPojo.getP1_MerId()),
            formatString(yeePayPojo.getP2_Order()), formatString(yeePayPojo.getP3_Amt()), formatString(yeePayPojo.getP4_Cur()), formatString(yeePayPojo.getP5_Pid()),
            formatString(yeePayPojo.getP6_Pcat()), formatString(yeePayPojo.getP7_Pdesc()), formatString(yeePayPojo.getP8_Url()), formatString(yeePayPojo.getP9_SAF()),
            formatString(yeePayPojo.getPa_MP()), formatString(yeePayPojo.getPd_FrpId()), formatString(yeePayPojo.getPr_NeedResponse()),
            formatString(Configuration.getInstance().getValue("keyValue")));
    yeePayPojo.setHmac(hmac);
    return yeePayPojo;
  }
  /**
   * 回调后通知商城信息
   * @param yeePay
   * @return
   */
  @Override
  public void callbacktoMerchant(YEEPay yeePay) {
    try{
      PayOrder payOrder = payOrderService.findByPayNumber(yeePay.getPayNum());
      PayDeal payDeal = new PayDeal();
      payDeal.setOrderNum(payOrder.getOrderNum());
      payDeal.setTotalCost(payOrder.getAmount());
      payDeal.setDealFee(yeePay.getAmt());
      payDeal.setDealState(yeePay.getResultCode());
      payDeal.setHmac(yeePay.getHmac() == null ? "" : yeePay.getHmac());
      payDeal.setDealId(yeePay.getTrxId());
      payDeal.setDealType("yeePay");
      payDeal.setPayTime(yeePay.getPayDate() == null ? new Date() : yeePay.getPayDate());
      payDeal.setPayType("gateway");
      payDeal.setPayee("");
      payDeal.setBankCardNo("");
      payDeal.setBankCardName("");
      payDeal.setPayNum(payOrder.getPayNum());
      //回调请求
      payOrderService.callbackToClient(payDeal,payOrder.getSourceType());
    } catch(Exception e){
      logger.info("订单推送三际商城失败===========" + e);
    }
  }

  private static String formatString(String text) {
    if (text == null) {
      return "";
    }
    return text;
  }
}
